#!/bin/bash
SCRIPT_BASE_DIR=$( dirname "${BASH_SOURCE[0]}" )
source "${SCRIPT_BASE_DIR}/common/ip_utils.sh"

set -e

function bring_dev_up() {
    # n="$1"
    # dest="$2"
    # sudo ip addr add 192.168.7.${n}/32 broadcast 192.168.7.255 dev ${tap}
    # sudo ip route add to 192.168.7.${dest} dev ${tap}
    # sudo iptables -A  POSTROUTING -t nat -j MASQUERADE -s 192.168.7.${n}/32
    # sudo iptables -A  POSTROUTING -t nat -j MASQUERADE -s 192.168.7.${dest}/32
    tap="$3"
    sudo ip link set dev ${tap} up
}

function set_up_net() {
    read -p "To create bridge br0 and virtual IF tap0, tap1?(Y/N)" -n 1 answer
    echo 
    
    if [ "Y" != "${answer^}" ]
    then
        exit
    fi

    sudo ip link add br0 type bridge

    sudo tunctl -u $(whoami)

    sudo ip link set tap0 master br0

    sudo tunctl -u $(whoami)

    sudo ip link set tap1 master br0
    
    sudo ip addr add 192.168.7.10/24 dev br0

    bring_dev_up 1 2 tap0

    bring_dev_up 3 4 tap1

    # sudo ip link set dev tap1 up
    sudo ip link set dev br0 up

    # 以下命令从poky/scripts/runqemu-ifup脚本得到
    sudo bash -c "echo 1 > /proc/sys/net/ipv4/ip_forward"
    sudo bash -c "echo 1 > /proc/sys/net/ipv4/conf/${tap}/proxy_arp"

    # 如果没有这一条命令，两个qemu实例之间ping不通
    sudo iptables  -P FORWARD ACCEPT

    # 下面的sysctl命令据说和上面iptables命令一样，但是还没试过
    # on ubuntu seems necessary to set this option to enable forwarding to other interfaces of the bridge
    # otherwise you can only ping the bridge IP address and not other systems via eth0
    # sudo sysctl net.bridge.bridge-nf-call-iptables=0
}

function clean_net() {
    read -p "To delete bridge br0 and virtual IF tap0, tap1?(Y/N)" -n 1 answer
    echo 
    
    if [ "Y" != "${answer^}" ]
    then
        exit
    fi

    sudo ip link delete br0
    sudo ip link delete tap0
    sudo ip link delete tap1
}

function usage() {
    echo "Usage: $( basename "$0" ) [-d | -h]"
    echo "    设置运行AP demo radar和fusion示例的虚拟网卡及网桥"
    echo "    设置的网卡名称为tap0, tap1, 网桥名称为br0"
    echo "    -d: 删除tap0, tap1, br0虚拟设备"
    echo "    -h: 输出本信息"
    exit 1
}

while getopts ":dh" arg
do
    case "${arg}" in
        d)
            clean_net 
            exit 0
            ;;
        d|*)
            usage;;
    esac
done

link_dev_none_or_die tap0
link_dev_none_or_die tap1
link_dev_none_or_die br0 

set_up_net
